Day 3: Lists
Creating Lists and Indexing
A list is an ordered, mutable collection.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
Slicing
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4]
print(nums[:3]) # [0, 1, 2]
print(nums[7:]) # [7, 8, 9]
print(nums[::2]) # [0, 2, 4, 6, 8]
print(nums[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Key Methods
| Method | Description | Example |
|---|---|---|
append(x) | Add to end | lst.append(4) |
insert(i, x) | Insert at position | lst.insert(0, "a") |
remove(x) | Remove by value | lst.remove("a") |
pop(i) | Remove and return by index | lst.pop(0) |
sort() | Sort | lst.sort() |
reverse() | Reverse | lst.reverse() |
index(x) | Find index of value | lst.index("a") |
count(x) | Count occurrences | lst.count(1) |
List Operations
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b) # [1, 2, 3, 4, 5, 6]
print(a * 2) # [1, 2, 3, 1, 2, 3]
print(3 in a) # True
print(len(a)) # 3
Today’s Exercises
- Take 5 numbers as input, store them in a list, and calculate the average.
- Create a new list with duplicate elements removed from the original list.
- Write a program that extracts only the common elements from two lists.